﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "iconhelper.h"
#include "myapp.h"
#include "netparamform.h"
#include "netparamplusform.h"
#include "checkboxheaderview.h"
#include <QSharedPointer>
#include "iplinkdialog.h"
#include "maskwidget.h"
#include "xlsxdocument.h"
#include "xlsxformat.h"
#include "xlsxcellrange.h"
#include "xlsxchart.h"




MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , complexsetform(NULL)
    , faceform(NULL)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint );
    this->setWindowTitle("PTU软件主界面");
    this->initForm();
//    timer = new QTimer(this);
//    timer->setInterval(10 * 1000);
//    connect(timer, &QTimer::timeout, this, &MainWindow::on_btn_refresh_clicked);
    this->initScanUdp();

    this->initWebsocket();

    MaskWidget::Instance()->setMainWidget(this);
    MaskWidget::Instance()->setDialogNames(QStringList() << "iplinkdialog" << "algosetform");
}

MainWindow::~MainWindow()
{
    qDebug() << "MainWindow close";

    delete ui;
}
void MainWindow::mousePressEvent(QMouseEvent* e)
{
    if(e->button() == Qt::LeftButton)
        clickPos = e->pos();
}
void MainWindow::mouseMoveEvent(QMouseEvent* e)
{
    if(e->buttons()&Qt::LeftButton)
    {
        if((e->pos() + pos() - clickPos) != QPoint(0, 0))
        {
            ui->btn_max->setChecked(false);
            on_btn_max_clicked(false);
            this->move(e->pos() + pos() - clickPos);
        }
    }
}

void MainWindow::initForm()
{
    ui->stackedWidget->setMinimumWidth(10);
    ui->stackedWidget->setMaximumWidth(10);
    ui->param_widget->setMinimumHeight(0);
    ui->param_widget->setMaximumHeight(0);
    ui->label_number->setText(QString::number(0));
    btn = new QPushButton(this);
    IconHelper::Instance()->setIcon(btn, 0xf104);
    btn->resize(20, 80);
    btn->move(this->width() - ui->stackedWidget->width() - 27, this
              ->height() / 2);

    connect(btn, &QPushButton::clicked, this, &MainWindow:: on_open_and_close_clicked);

    QHBoxLayout* pSearchLayout = new QHBoxLayout(ui->lineEdit_search);
    pSearchLayout->addStretch();
    pSearchLayout->setSpacing(0);
    pSearchLayout->setContentsMargins(0, 0, 0, 0);
    QPushButton* search = new QPushButton(this);
    search->resize(ui->lineEdit_search->height(), ui->lineEdit_search->height());
    search->setFocusPolicy(Qt::NoFocus);
    search->setCursor(QCursor(Qt::PointingHandCursor));
    search->setFlat(true);
    search->setStyleSheet("background-color: rgb(9, 19, 50);color: rgb(255, 255, 255);"
                          "width:24px;height:24px;margin:2px;");
    //connect(search, &QPushButton::clicked, this, &MainWindow::btn_search_clicked);
    QPixmap pix = IconHelper::Instance()->getPixmap("#255990", 0xf002, 30, 28, 28);
    search->setIcon(pix);
    pSearchLayout->addWidget(search);
    ui->lineEdit_search->setTextMargins(0, 0,  ui->lineEdit_search->height(), 0);
    ui->lineEdit_search->setPlaceholderText("筛选");


    QStringList header;
    header <<  "编号" << "设备类型"  << "ip地址" << "端口"
           << "物理地址1" << "物理地址2" << "板卡SN"  << "生产日期" ;

    ui->tableWidget->setColumnCount(header.size());
    ui->tableWidget->setHorizontalHeaderLabels(header);
    ui->tableWidget->setColumnWidth(0, 50);
    for (int i = 1; i < header.size(); i++)
    {
        ui->tableWidget->setColumnWidth(i, 170);
    }
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    //  ui->tableWidget->setAlternatingRowColors(true);
    //ui->tableWidget->resizeColumnsToContents();
    // ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//根据容器调整大小
    ui->tableWidget->verticalHeader()->setHidden(true);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);

#if 0
    //表格多选按钮
    CheckBoxHeaderView* m_checkHeaderView = new CheckBoxHeaderView(0, QPoint(3, 3), QSize(11, 11 ), Qt::Horizontal, this);
    m_checkHeaderView->setObjectName(QStringLiteral("m_checkHeaderView"));
    ui->tableWidget->setHorizontalHeader( m_checkHeaderView );
    connect(m_checkHeaderView, &CheckBoxHeaderView::checkStatusChange, this, [ = ]
    {
        if(m_checkHeaderView->GetCheckState())
        {
            for(int i = 0; i < ui->tableWidget->rowCount(); i++)
            {
                ui->tableWidget->item(i, 0)->setCheckState(Qt::Checked);
            }
        }
        else
        {
            for(int i = 0; i < ui->tableWidget->rowCount(); i++)
            {
                ui->tableWidget->item(i, 0)->setCheckState(Qt::Unchecked);
            }
        }
    });
#endif


    QString version = qApp->applicationVersion();
    version = version.mid(0, version.lastIndexOf('.'));
    //int index = version.length() - (version.section('.', 3, 3).length() + 1);
    info_about = new about( QString("PTU %1").arg(version), this);
    info_about->hide();

    connect(this, &MainWindow::netparam, ui->netparam, &NetParamForm::onNetworkParam);
    connect(this, &MainWindow::siggetnetparam, ui->netparam, &NetParamForm::onGetNetparam);
    connect(this, &MainWindow::lock, ui->netparam, &NetParamForm::clear);
    connect(ui->netparam, &NetParamForm::sigSendUdpParam, this, &MainWindow::onSendUdpParam);


#if TEST

    int row = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(row);

    ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1)));
    ui->tableWidget->item(row, 0)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->tableWidget->setItem(row, 1, new QTableWidgetItem("AI高速相机"));
    ui->tableWidget->setItem(row, 2, new QTableWidgetItem("127.0.0.1"));
    ui->tableWidget->setItem(row, 3, new QTableWidgetItem("1"));
    ui->tableWidget->setItem(row, 4, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 5, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 6, new QTableWidgetItem("0"));

    row++;
    ui->tableWidget->insertRow(row);
    ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1)));
    ui->tableWidget->item(row, 0)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->tableWidget->setItem(row, 1, new QTableWidgetItem("AI中低速相机"));
    ui->tableWidget->setItem(row, 2, new QTableWidgetItem("169.254.239.60"));
    ui->tableWidget->setItem(row, 3, new QTableWidgetItem("12"));
    ui->tableWidget->setItem(row, 4, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 5, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 6, new QTableWidgetItem("0"));

    row++;
    ui->tableWidget->insertRow(row);
    ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1)));
    ui->tableWidget->item(row, 0)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->tableWidget->setItem(row, 1, new QTableWidgetItem("分析装置"));
    ui->tableWidget->setItem(row, 2, new QTableWidgetItem("192.168.2.105"));
    ui->tableWidget->setItem(row, 3, new QTableWidgetItem("8101"));
    ui->tableWidget->setItem(row, 4, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 5, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 6, new QTableWidgetItem("0"));

    row++;
    ui->tableWidget->insertRow(row);
    ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1)));
    ui->tableWidget->item(row, 0)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->tableWidget->setItem(row, 1, new QTableWidgetItem("GPU服务器"));
    ui->tableWidget->setItem(row, 2, new QTableWidgetItem("435"));
    ui->tableWidget->setItem(row, 3, new QTableWidgetItem("1234"));
    ui->tableWidget->setItem(row, 4, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 5, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 6, new QTableWidgetItem("0"));
    ui->label_number->setText(QString::number(row + 1));

    row++;
    ui->tableWidget->insertRow(row);
    ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1)));
    ui->tableWidget->item(row, 0)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->tableWidget->setItem(row, 1, new QTableWidgetItem("人脸服务器"));
    ui->tableWidget->setItem(row, 2, new QTableWidgetItem("www.haitutech.net"));
    ui->tableWidget->setItem(row, 3, new QTableWidgetItem("1234"));
    ui->tableWidget->setItem(row, 4, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 5, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 6, new QTableWidgetItem("0"));
    ui->label_number->setText(QString::number(row + 1));

    row++;
    ui->tableWidget->insertRow(row);
    ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1)));
    ui->tableWidget->item(row, 0)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->tableWidget->setItem(row, 1, new QTableWidgetItem("电子封条分析装置"));
    ui->tableWidget->setItem(row, 2, new QTableWidgetItem("www.haitutech.net"));
    ui->tableWidget->setItem(row, 3, new QTableWidgetItem("1234"));
    ui->tableWidget->setItem(row, 4, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 5, new QTableWidgetItem("123"));
    ui->tableWidget->setItem(row, 6, new QTableWidgetItem("0"));
    ui->label_number->setText(QString::number(row + 1));

#endif


}
void  MainWindow::initWebsocket()
{
    m_aiWebsocket = new AiWebsocket(this);
    connect(m_aiWebsocket, &AiWebsocket::sigConnectState, this, &MainWindow::onConnectState);
    connect(m_aiWebsocket, &AiWebsocket::sigConnectFail, this, []
    {
        QMessageBox::critical(nullptr, "警告", "连接失败");
    });
    /*
    @ Kind   : Change
    @ Author : Wei.Liu
    @ Date   : 2022-08-17
    @ Brief  : 重新修改连接逻辑，删除自动重连功能
    */
//    connect(m_aiWebsocket, &AiWebsocket::sigReconnect, this, [ = ]()
//    {
//        qDebug() << "sig_reconnect";
//        QTimer::singleShot(15 * 1000, this, [ = ]()
//        {
//            this->on_btn_link_clicked();
//        });
//    });
}


void MainWindow::onSendUdpParam(DevScan devScan)
{
    int row = ui->tableWidget->currentRow();
    QByteArray devScanArr;
    devScanArr.append((char*)&devScan, sizeof(devScan));

    if(m_scanUdp)
    {
        m_scanUdp->writeDatagram(devScanArr, QHostAddress(ui->tableWidget->item(row, 2)->text()), ui->tableWidget->item(row, 3)->text().toUInt());
        qInfo() << "udpsend: " << "ocmd" << devScan.ocmd << "contentLen:" << devScan.contentLen;

    }
}

void MainWindow::initScanUdp()
{
    m_scanUdp = new QUdpSocket(this);
    if(m_scanUdp->state() == QUdpSocket::BoundState)
    {
        m_scanUdp->leaveMulticastGroup(QHostAddress(MULTICAST_ADDR));
        m_scanUdp->abort();
    }

    if(m_scanUdp->bind(QHostAddress::AnyIPv4, MULTICAST_PORT, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint))
    {
        qInfo() << "bind MulticastPort:" << MULTICAST_PORT << "success";

        if(m_scanUdp->joinMulticastGroup(QHostAddress(MULTICAST_ADDR)))
        {
            qInfo() << "join multcast:" << MULTICAST_ADDR << "success";
            //设置缓冲区
            m_scanUdp->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, 1024 * 1024 * 8);
            //连接接收信号槽
            connect(m_scanUdp, &QUdpSocket::readyRead, this, &MainWindow::onScanUdpReadyRead);
        }
        else
        {
            qInfo() << "join multcast:" << MULTICAST_ADDR << "failed";
        }
    }
    else
    {
        qInfo() << "bind MulticastPort:" << MULTICAST_PORT << "failed";
    }
#if not TEST
    this->on_btn_refresh_clicked();
#endif


}

void MainWindow::onScanUdpReadyRead()
{
    while(m_scanUdp->hasPendingDatagrams())
    {

        QHostAddress hostAddr;
        quint16 port;
        //qInfo() << "udprec:size:" << m_scanUdp->pendingDatagramSize();
        if(m_scanUdp->pendingDatagramSize() == 279)
        {
            DevScan devcan;
            DeviceInfoStruct devinfo;
            memset(&devcan, 0, sizeof (devcan));
            memset(&devinfo, 0, sizeof (devinfo));
            m_scanUdp->readDatagram((char*)&devcan, sizeof(devcan), &hostAddr, &port);
            //qInfo() << "udprec:ocmd:" << devcan.ocmd << "contentstr:" << devcan.contentstr;
            if(devcan.ocmd == DEVICE_DISCOVER_CMD_RESP)
            {
                memcpy(&devinfo, devcan.contentstr, sizeof(devinfo));
                QString devIp = hostAddr.toString();
                bool exist = false;
                int row = ui->tableWidget->rowCount();
                for(int i = 0; i < row ; i++)
                {
                    if(ui->tableWidget->item(i, 2)->text() == devIp)
                    {
                        exist = true;
                        break;
                    }
                }
                if(!exist)
                {
                    ui->tableWidget->insertRow(row);
                    ui->tableWidget->setRowHeight(row, 24);
                    ui->label_number->setText(QString::number(row + 1));
//表格check按键
//                    QTableWidgetItem* p_check = new QTableWidgetItem();
//                    p_check->setCheckState(Qt::Unchecked);
//                    ui->tableWidget->setItem(row, 0, p_check);
                    ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1)));
                    ui->tableWidget->item(row, 0)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                    QStringList dev = QString(devinfo.devType).split("-");
                    if(dev.at(0) == "AiCam_H")ui->tableWidget->setItem(row, 1, new QTableWidgetItem(myApp::AiCam_H));
                    else if(dev.at(0) == "AiCam_L")ui->tableWidget->setItem(row, 1, new QTableWidgetItem(myApp::AiCam_L));
                    else if(dev.at(0) == "Ai_ARM")ui->tableWidget->setItem(row, 1, new QTableWidgetItem(myApp::Ai_ARM));
                    else if(dev.at(0) == "Ai_GPU")ui->tableWidget->setItem(row, 1, new QTableWidgetItem(myApp::Ai_GPU));
                    else if(dev.at(0) == "Ai_FACE")ui->tableWidget->setItem(row, 1, new QTableWidgetItem(myApp::Ai_FACE));
                    else if(dev.at(0) == "Ai_DZFT")ui->tableWidget->setItem(row, 1, new QTableWidgetItem(myApp::Ai_DZFT));
                    ui->tableWidget->setItem(row, 2, new QTableWidgetItem(devIp));

                    ui->tableWidget->setItem(row, 3, new QTableWidgetItem(QString::number(port)));

                    ui->tableWidget->setItem(row, 4, new QTableWidgetItem(QString(devinfo.mac0)));

                    ui->tableWidget->setItem(row, 5, new QTableWidgetItem(QString(devinfo.mac1)));

                    ui->tableWidget->setItem(row, 6, new QTableWidgetItem(QString((devinfo.sn))));

                    ui->tableWidget->setItem(row, 7, new QTableWidgetItem(QString(devinfo.date)));

                }
            }
            else if(devcan.ocmd == DEVICE_GET_NETWORK_CMD_RESP)
            {
                NetParam netparam;
                memset(&netparam, 0, sizeof (netparam));
                memcpy(&netparam, devcan.contentstr, sizeof(netparam));
                emit siggetnetparam(netparam);

            }
            else if(devcan.ocmd == DEVICE_SET_NETWORK_CMD_RESP)
            {
                //设置网络参数成功
                //请求是否重启
                QMessageBox m_box(QMessageBox::Question, QString("请求"), QString("是否重启设备"), QMessageBox::Ok | QMessageBox::Cancel);
                if(m_box.exec() == QMessageBox::Ok)
                {
                    DevScan devScan;
                    memset(&devScan, 0, sizeof(devScan));
                    devScan.ocmd = DEVICE_SET_REBOOT_CMD;
                    this->onSendUdpParam(devScan);//重启
                }
            }
            else if(devcan.ocmd == DEVICE_SET_REBOOT_CMD_RESP)
            {
                //重启成功
                QMessageBox m_box(QMessageBox::Information, QString("通知"), QString("重启成功"), QMessageBox::Ok );
                m_box.exec();
            }
        }
        else
        {
            QByteArray arr;
            arr.resize(m_scanUdp->pendingDatagramSize());
            m_scanUdp->readDatagram(arr.data(), arr.size(), &hostAddr, &port);
        }

#if 0
        QHostAddress hostAddr;
        quint16 port;
        DevScan devcan;
        DeviceInfoStruct devinfo;
        memset(&devcan, 0, sizeof (devcan));
        memset(&devinfo, 0, sizeof (devinfo));
        m_scanUdp->readDatagram((char*)&devcan, sizeof(devcan), &hostAddr, &port);
        memcpy(&devinfo, devcan.contentstr, sizeof(devcan.contentstr));
        QString devIp = hostAddr.toString();
        //   QString devType(content);
        qDebug() << devIp << devinfo.devType;
#endif
    }
}


void MainWindow::on_open_and_close_clicked()
{
    if(ui->stackedWidget->width() == 10)
    {
        ui->stackedWidget->setMinimumWidth(300);
        ui->stackedWidget->setMaximumWidth(300);
        btn->move(this->width() - ui->stackedWidget->width() - 27, this
                  ->height() / 2);
        IconHelper::Instance()->setIcon(btn, 0xf105);

    }
    else
    {
        ui->stackedWidget->setMinimumWidth(10);
        ui->stackedWidget->setMaximumWidth(10);
        btn->move(this->width() - ui->stackedWidget->width() - 27, this
                  ->height() / 2);
        IconHelper::Instance()->setIcon(btn, 0xf104);
    }

}

void MainWindow::on_btn_close_clicked()
{
    bool ok = this->close();
}

void MainWindow::closeEvent(QCloseEvent* event)
{
    Q_UNUSED(event);
    if(m_aiWebsocket != NULL)
    {
        if(m_aiWebsocket->connected())
        {
            m_aiWebsocket->disconn();
        }
        m_aiWebsocket->terminate();
        //m_aiWebsocket->deleteLater();
    }

}

void MainWindow::on_btn_about_clicked(bool checked)
{

    if(checked)
    {
        info_about->move(ui->btn_about->geometry().left() - 150, ui->btn_about->geometry().bottom() + 10);
        info_about->show();
    }
    else
    {
        info_about->hide();
    }
}

void MainWindow::on_btn_refresh_clicked()
{
    for(int row = ui->tableWidget->rowCount() - 1; row >= 0; row--)
    {
        ui->tableWidget->removeRow(row);
        ui->label_number->setNum(row);
    }
    DevScan devScan;
    memset(&devScan, 0, sizeof(devScan));
    devScan.ocmd = DEVICE_DISCOVER_CMD;

    QByteArray devScanArr;
    devScanArr.append((char*)&devScan, sizeof(devScan));

    if(m_scanUdp)
    {
        m_scanUdp->writeDatagram(devScanArr, QHostAddress(MULTICAST_ADDR), MULTICAST_PORT);
        qDebug() << "udpsendgroup";
    }
//    if(!timer->isActive())timer->start();
}

void MainWindow::on_btn_min_clicked()
{
    this->showMinimized();
}

void MainWindow::on_btn_max_clicked(bool checked)
{
    if(checked)
    {
        this->showFullScreen();
        ui->btn_max->setStyleSheet("QPushButton{ border-image: url(:/image/normal.png);}"
                                   "QPushButton:hover{border-image: url(:/image/normal_hover.png);}");
        btn->move(this->width() - ui->stackedWidget->width() - 27, this->height() / 2);
        info_about->move(ui->btn_about->geometry().left() - 150, ui->btn_about->geometry().bottom() + 10);
        if(complexsetform != NULL)
            complexsetform->resize(ui->centralwidget->width(), ui->centralwidget->height() - ui->widget_top->height());
    }
    else
    {
        this->showNormal();
        ui->btn_max->setStyleSheet("QPushButton{ border-image: url(:/image/max.png);}"
                                   "QPushButton:hover{border-image: url(:/image/max_hover.png);}");
        btn->move(this->width() - ui->stackedWidget->width() - 27, this->height() / 2);
        info_about->move(ui->btn_about->geometry().left() - 150, ui->btn_about->geometry().bottom() + 10);
        if(complexsetform != NULL)
            complexsetform->resize(ui->centralwidget->width(), ui->centralwidget->height() - ui->widget_top->height());
    }
}

void MainWindow::on_tableWidget_cellChanged(int row, int column)
{
#if 0
    if(column == 0)
    {
        if(ui->tableWidget->item(row, 0)->checkState() == Qt::Checked)
        {
            ui->tableWidget->selectRow(row);
            rows.append(row);
        }
        if(ui->tableWidget->item(row, 0)->checkState() == Qt::Unchecked)
        {
            ui->tableWidget->setCurrentItem(NULL);
            for (int i = 0; i < rows.count(); i++)
            {
                if(rows.at(i) == row)
                    rows.removeAt(i);
            }
        }
    }
    if(rows.count() == 1)
    {
        ui->stackedWidget->setCurrentIndex(0);
//        NetworkParam net_param;
//        net_param.devtype = ui->tableWidget->item(rows.at(0), 2)->text();
//        net_param.port = ui->tableWidget->item(rows.at(0), 4)->text();
//        net_param.sn = ui->tableWidget->item(rows.at(0), 7)->text();
//        // net_param.gateway_v6 = ui->tableWidget->item(rows.at(0), 9)->text();
//        emit netparam(net_param);
        this-> on_tableWidget_cellClicked(rows.at(0), 0);
//        DevScan devScan;
//        memset(&devScan, 0, sizeof(devScan));
//        devScan.ocmd = DEVICE_DISCOVER_CMD;
//        this->onSendUdpParam(devScan);

    }
    else if(rows.count() > 1)
    {
        ui->stackedWidget->setCurrentIndex(1);
    }
    else
    {
        ui->stackedWidget->setCurrentIndex(0);
        emit lock();
    }
#endif
}

void MainWindow::on_tableWidget_cellDoubleClicked(int row, int column)
{

    // 测试相关
#if TEST
    if(ui->tableWidget->item(row, 1)->text() == "人脸服务器")
    {
        faceform = new AiFaceForm(ui->tableWidget->item(row, 2)->text(), this);
        ui->param_widget->setMinimumHeight(ui->centralwidget->height() * 0.5);
        ui->param_widget->setMaximumHeight(ui->centralwidget->height() * 0.67);
        ui->param_widget->resize(ui->tableWidget->width(), ui->centralwidget->height() * 0.67);
        faceform->setParent(ui->param_widget);
        faceform->resize(ui->param_widget->width(), ui->param_widget->height());
        faceform->show();
        ui->btn_link->setText("断开");
        ui->btn_link->setStyleSheet("QPushButton { background-color: green; color: white;}");
    }
    else
    {
        complexsetform = new ComplexSetForm(ui->tableWidget->item(row, 1)->text(), this);
        ui->param_widget->setMinimumHeight(ui->centralwidget->height() * 0.5);
        ui->param_widget->setMaximumHeight(ui->centralwidget->height() * 0.67);
        ui->param_widget->resize(ui->tableWidget->width(), ui->centralwidget->height() * 0.67);
        complexsetform->setParent(ui->param_widget);
        complexsetform->resize(ui->param_widget->width(), ui->param_widget->height());
        complexsetform->show();
    }
#endif
#if not TEST
    if(ui->tableWidget->item(row, 1)->text() == "人脸服务器")
    {
        faceform = new AiFaceForm(ui->tableWidget->item(row, 2)->text(), this);
        ui->param_widget->setMinimumHeight(ui->centralwidget->height() * 0.5);
        ui->param_widget->setMaximumHeight(ui->centralwidget->height() * 0.67);
        ui->param_widget->resize(ui->tableWidget->width(), ui->centralwidget->height() * 0.67);
        faceform->setParent(ui->param_widget);
        faceform->resize(ui->param_widget->width(), ui->param_widget->height());
        faceform->show();
        ui->btn_link->setText("断开");
        ui->btn_link->setStyleSheet("QPushButton { background-color: green; color: white;}");
    }
    else
    {
        if(m_aiWebsocket->connected())
        {
            m_aiWebsocket->disconn();
        }
        m_aiWebsocket->conn(QString("ws://%1:%2").arg(ui->tableWidget->item(row, 2)->text()).arg(8108));
    }
#endif
}

void MainWindow::on_btn_link_clicked(bool checked)
{

}

void MainWindow::onlinkwebsocket(QString str)
{
    if(str.startsWith("ws:"))
    {
        m_aiWebsocket->conn(str);
        qDebug() << "websocket connect:" << str;
    }
    else
    {
        faceform = new AiFaceForm(str, this);
        ui->param_widget->setMinimumHeight(ui->centralwidget->height() * 0.5);
        ui->param_widget->setMaximumHeight(ui->centralwidget->height() * 0.67);
        ui->param_widget->resize(ui->tableWidget->width(), ui->centralwidget->height() * 0.67);
        faceform->setParent(ui->param_widget);
        faceform->resize(ui->param_widget->width(), ui->param_widget->height());
        faceform->show();
        ui->btn_link->setText("断开");
        ui->btn_link->setStyleSheet("QPushButton { background-color: green; color: white;}");
    }

}
void MainWindow::onConnectState(bool state)
{
    if(state)
    {

        int row = ui->tableWidget->currentRow();
        ui->btn_link->setText("断开");
        ui->btn_link->setStyleSheet("QPushButton { background-color: green; color: white;}");
//        if(timer->isActive())timer->stop();
        if(row < 0)
        {
            complexsetform = new ComplexSetForm("", this);
            ui->param_widget->setMinimumHeight(ui->centralwidget->height() * 0.5);
            ui->param_widget->setMaximumHeight(ui->centralwidget->height() * 0.67);
            ui->param_widget->resize(ui->tableWidget->width(), ui->centralwidget->height() * 0.67);
            complexsetform->setParent(ui->param_widget);
            complexsetform->resize(ui->param_widget->width(), ui->param_widget->height());
            complexsetform->show();
        }
        else
        {
            if(ui->tableWidget->item(row, 1) != NULL)
            {
                complexsetform = new ComplexSetForm(ui->tableWidget->item(row, 1)->text(), this);
                ui->param_widget->setMinimumHeight(ui->centralwidget->height() * 0.5);
                ui->param_widget->setMaximumHeight(ui->centralwidget->height() * 0.67);
                ui->param_widget->resize(ui->tableWidget->width(), ui->centralwidget->height() * 0.67);
                complexsetform->setParent(ui->param_widget);
                complexsetform->resize(ui->param_widget->width(), ui->param_widget->height());
                complexsetform->show();
            }
        }
    }
    else
    {
        //QMessageBox::warning(this, "警告", "连接失败", QMessageBox::Ok, QMessageBox::NoButton);
        ui->btn_link->setText("连接");
        ui->btn_link->setStyleSheet("QPushButton { background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(8, 138, 247, 255), stop:1 rgba(8, 106, 247, 255))}");
        qDebug() << "connect close";
//        if(!timer->isActive())timer->start();
        ui->param_widget->setMinimumHeight(0);
        ui->param_widget->setMaximumHeight(0);

//        if(complexsetform != NULL)
//            complexsetform->close();
    }
}

void MainWindow::on_tableWidget_cellClicked(int row, int column)
{
//    if(timer->isActive())timer->stop();
    DevScan devScan;
    memset(&devScan, 0, sizeof(devScan));
    devScan.ocmd = DEVICE_GET_NETWORK_CMD;
    this->onSendUdpParam(devScan);

    NetworkParam net_param;
    net_param.devtype = ui->tableWidget->item(row, 1)->text();
    net_param.port = ui->tableWidget->item(row, 3)->text();
    net_param.sn = ui->tableWidget->item(row, 6)->text();
    emit netparam(net_param);
}

void MainWindow::on_lineEdit_search_textChanged(const QString& arg)
{

    if(arg != NULL)
    {
        for (int i = 0; i < ui->tableWidget->rowCount(); i++)
        {
            ui->tableWidget->setRowHidden(i, true);
            for (int j = 0; j < ui->tableWidget->columnCount(); j++)
            {
                if(ui->tableWidget->item(i, j) != NULL)
                {
                    if(ui->tableWidget->item(i, j)->text().contains(arg, Qt::CaseSensitive))
                    {
                        ui->tableWidget->setRowHidden(i, false);
                    }
                }
            }
        }
    }
    else
    {
        for (int i = 0; i < ui->tableWidget->rowCount(); i++)
        {
            ui->tableWidget->setRowHidden(i, false);
        }
    }
}

void MainWindow::on_btn_out_clicked()
{
    QString filepath = QFileDialog::getSaveFileName(this, tr("保存设备列表"), ".", tr(" (*.xlsx)"));
    if(!filepath.isEmpty())
    {
        QXlsx::Document xlsx;
        QXlsx::Format format1;/*设置该单元的样式*/
        format1.setFontColor(Qt::white);/*文字为红色*/
        format1.setPatternBackgroundColor("#091332"); /*背景颜色*/
        format1.setFontSize(12);/*设置字体大小*/
        format1.setHorizontalAlignment(QXlsx::Format::AlignHCenter);/*横向居中*/
        format1.setBorderStyle(QXlsx::Format::BorderDashDotDot);/*边框样式*/
        QXlsx::Format format2;
        format2.setFontSize(12);
        format2.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
        format2.setFontColor(QColor(37, 89, 144));/*文字为红色*/
        format2.setPatternBackgroundColor("#091332"); /*背景颜色*/
        if(!xlsx.selectSheet("ptu")) /*在当前打开的xlsx文件中，找一个名字为ptu的sheet*/
        {
            xlsx.addSheet("ptu");//找不到的话就添加一个名为ptu的sheet
        }
        for (int i = 0; i < ui->tableWidget->horizontalHeader()->count(); ++i)
        {
            xlsx.write(1, i + 1, ui->tableWidget->horizontalHeaderItem(i)->text(), format1);
        }
        for (int i = 0; i < ui->tableWidget->rowCount(); ++i)
        {
            for (int j = 0; j < ui->tableWidget->columnCount(); ++j)
            {

                if(ui->tableWidget->item(i, j) != NULL)
                    xlsx.write(i + 2, j + 1, ui->tableWidget->item(i, j)->text(), format2);
            }
        }
        xlsx.saveAs(QDir::toNativeSeparators(filepath));/*保存*/
    }
}

void MainWindow::on_btn_link_clicked()
{

    if(ui->btn_link->text() == "连接")
    {
        qDebug() << "connect";
        int row = ui->tableWidget->currentRow();
        if(row < 0)
        {
            IpLinkDialog dlg;
            connect(&dlg, &IpLinkDialog::linkwebsocket, this, &MainWindow::onlinkwebsocket);
            dlg.setObjectName("iplinkdialog");
            dlg.setFixedSize(331, 244);
            //dlg.move((this->geometry().width() - dlg.geometry().width()) / 2, (this->geometry().height() - dlg.geometry().height()) / 2);
            dlg.exec();
        }
        else
        {
            if(ui->tableWidget->item(row, 1)->text() == "人脸服务器")
            {
                faceform = new AiFaceForm(ui->tableWidget->item(row, 2)->text(), this);
                ui->param_widget->setMinimumHeight(ui->centralwidget->height() * 0.5);
                ui->param_widget->setMaximumHeight(ui->centralwidget->height() * 0.67);
                ui->param_widget->resize(ui->tableWidget->width(), ui->centralwidget->height() * 0.67);
                faceform->setParent(ui->param_widget);
                faceform->resize(ui->param_widget->width(), ui->param_widget->height());
                faceform->show();
                ui->btn_link->setText("断开");
                ui->btn_link->setStyleSheet("QPushButton { background-color: green; color: white;}");
            }
            else
            {
                m_aiWebsocket->conn(QString("ws://%1:%2").arg(ui->tableWidget->item(row, 2)->text()).arg(8108));
                qDebug() << "connect:" << ui->tableWidget->item(row, 2)->text();
            }
        }
    }
    else
    {
        if(m_aiWebsocket->connected())
        {
            m_aiWebsocket->disconn();
            qDebug() << "disconn";
        }
        if(faceform != nullptr)
        {
            qDebug() << "faceform close~";
            faceform->close();
            faceform = nullptr;
            ui->param_widget->setMinimumHeight(0);
            ui->param_widget->setMaximumHeight(0);
            ui->btn_link->setText("连接");
            ui->btn_link->setStyleSheet("QPushButton { background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(8, 138, 247, 255), stop:1 rgba(8, 106, 247, 255))}");
        }
    }
}


